import style from './index.module.less'
import { Form, Button, Toast, Dialog, CascadePicker } from 'antd-mobile'
import PageComponent from '@components/pageComponent'
import { getCaseDetailRequest, updateData, getTreeRequest } from './ajax'
import { awaitWrap } from '@src/assets/js/tool'
import { useEffect, useState } from 'react'
import { refreshCaseEditVersion } from '@src/redux/reducers/cases'
import { pop } from '@src/redux/reducers/pages'
import { useAppDispatch } from '@src/redux/hook'
import TreePicker from '@components/treePicker'

const { Item, useForm } = Form

async function initData (caseid, formRef, setData) {
  Toast.show({ content: '加载中', icon: 'loading', duration: 0 })
  const [e, d] = await awaitWrap(getCaseDetailRequest(caseid))
  if (e === null) {
    Toast.clear()
    if (d) {
      setData(d)
      formRef.setFieldsValue({
        cause_action: d.cause_action || ''
      })
    }
  }
}

async function submitHandle (caseid, d, caseDetail, dispatch) {
  Toast.show({ content: '提交中', icon: 'loading', duration: 0 })
  const [e] = await awaitWrap(updateData(caseid, { cause_action: d.cause_action }))
  if (e === null) {
    Toast.clear()
    Toast.show({ content: '提交成功', icon: 'success' })
    dispatch(refreshCaseEditVersion())
    dispatch(pop())
  }
}

async function initTree (setData) {
  const [e, d] = await awaitWrap(getTreeRequest())
  if (e === null && d !== null) {
    setData(d)
  }
}

function Main ({ meta: { caseid = '' } = { case: '' } }) {
  const [formRef] = useForm()
  const dispatch = useAppDispatch()
  const [data, setData] = useState(null)
  const [options, setOptions] = useState([])
  useEffect(() => {
    if (formRef && caseid) {
      initData(caseid, formRef, setData)
    }
  }, [caseid, formRef])
  useEffect(() => {
    initTree(setOptions)
  }, [])
  return (
    <PageComponent title='编辑案由'>
      <Form layout='horizontal' form={formRef} onFinish={d => {
        Dialog.confirm({
          title: '您确定要提交吗？',
          onConfirm: () => {
            submitHandle(caseid, d, data, dispatch)
          }
        })
      }}>
        <TreePicker name='cause_action' label='案由' options={options} formRef={formRef} />
        <Item>
          <div className={style.btns}>
            <Button type='submit' color='primary' block>提交</Button>
          </div>
        </Item>
      </Form>
    </PageComponent>
  )
}

export default Main
